<?php
$db = new SQLite3("students.db");

function generatePassword($pwd) {
    $p = sha1($pwd);
    $salt = md5(rand());
    return substr($salt, 0, 4).substr($p, 0, 15);
}

function equalPassword($raw, $pwd) {
    $la = substr(sha1($raw), 0, 15);
    $lb = substr($pwd, 4, 15);
    return $la == $lb;
}

function checkPassword($username, $password) {
    global $db;
    $stmt = $db->prepare("select password from users where username=:username");
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $result = $stmt->execute();
    if ($result && $result->numColumns()) {
        $p = $result->fetchArray(SQLITE3_NUM)[0];
        if (equalPassword($password, $p)) return 0;
        return 1;
    }
    return -1;
}

function ifExistUser($username) {
    global $db;
    $stmt = $db->prepare("select password from users where username=:username");
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $result = $stmt->execute();
    if ($result->numColumns() && $result->columnType(0) != SQLITE3_NULL) {
        return true;
    }
    return false;
}
?>